import smtplib
import random
import string
from email.mime.text import MIMEText
from django.conf import settings
def generate_random_code(length=6):
    """生成包含数字和字母（区分大小写）的随机验证码"""
    characters = string.ascii_letters + string.digits  # 包含大小写字母和数字
    return ''.join(random.choice(characters) for _ in range(length))

def send_verification_code(email_receiver):
    """ 发送验证码 """
    # 生成6位随机验证码（包含数字和字母，区分大小写）
    verification_code = generate_random_code(6)
    
    # 邮件内容
    mail_content = f"""
    尊敬的用户：
    
    您的验证码是：{verification_code}
    
    请在5分钟内完成验证。如非本人操作，请忽略此邮件。
    
    注意：验证码区分大小写，请准确输入。
    
    感谢您的使用！
    """
    
    # 设置邮件信息
    message = MIMEText(mail_content, 'plain', 'utf-8')
    message['From'] = settings.EMAIL_HOST_USER  # 直接使用邮箱地址
    message['To'] = email_receiver
    message['Subject'] = "您的验证码（区分大小写, 请勿回复）"
    
    try:
        # 连接SMTP服务器
        with smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT) as server:
            server.starttls()  # 启用TLS加密
            server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
            server.sendmail(settings.EMAIL_HOST_USER, [email_receiver], message.as_string())
        
        print(f"验证码已发送至 {email_receiver}")
        return verification_code
    
    except Exception as e:
        
        print(f"发送邮件时出错: {e}")
        return None


